<template>
  <div class="templateContentDetail">
    <navigation-title>
      <div class="create_box">
      </div>
    </navigation-title>
    <div class="header">
      <el-button type="danger" :icon="Delete" @click="deleteItemAll"> {{
        $t('teamDoc.temp.btn1') }} </el-button>
      <el-button :icon="Plus" type="primary" @click="addItem">{{ $t('teamDoc.temp.btn2') }}</el-button>
      <el-button :icon="Plus" type="success" @click="batchItem">{{ $t('teamDoc.temp.btn3') }}</el-button>
    </div>
    <div class="header" style="margin: 20px;margin-bottom: 0;">
      <!-- 表单数据 -->
      <el-form  :inline="true" :model="searchData" class="demo-form-inline">
        <el-form-item :label="$t('teamDoc.temp.tempName')">
          <el-input v-model="searchData.name" :placeholder="$t('teamDoc.temp.tempName')"></el-input>
        </el-form-item>

        <el-form-item :label="$t('teamDoc.temp.docType')" prop="title">
          <el-select v-model="searchData.title" :placeholder="$t('teamDoc.temp.plaHold1')">
            <el-option :label="$t('teamDoc.temp.all')" value=""></el-option>
            <el-option label="word" value="word"></el-option>
            <el-option label="excel" value="excel"></el-option>
            <el-option label="ppt" value="ppt"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchForm()">{{ $t('commen.search') }}</el-button>
          <el-button @click="resetForm">{{ $t('commen.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格数据 -->
    <div class="content">
      <div class="content-top">
        <el-table :data="tableData" style="width: 100%" v-loading="Dialogloading" @selection-change="selectRow">
          <el-table-column :label="$t('teamDoc.temp.tempName')">
            <template #default="scope">

              <span style="margin-left: 10px">{{ scope.row.realName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" :label="$t('teamDoc.temp.docType')"> </el-table-column>
          <el-table-column :label="$t('commen.operation')" width="200">
            <template #default="scope">
              <el-button type="success" :icon="Edit" @click="edit(scope.row)"></el-button>
              <el-button type="danger" :icon="Delete" @click="del(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分页数据 -->
    <el-pagination @size-change="sizeChange" @current-change="currentPage" :current-page="page"
      :page-sizes="[6, 12, 18, 24]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 修改信息弹出框 -->
    <el-dialog :title="dialogTitle" v-model="flag" width="30%" destroy-on-close>
      <el-form :model="form" :rules="rules" ref="ruleFormRef">
        <el-form-item :label="$t('teamDoc.temp.tempName')" :label-width="formLabelWidth" prop="realName">
          <el-input v-model="form.realName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('teamDoc.temp.file')" :label-width="formLabelWidth" :required="isAdd">
          <uploadFile :limit="1" ref="UploadFile" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="flag = false">{{ $t('commen.cancel') }}</el-button>
        <el-button type="primary" @click="saveEdit(ruleFormRef)">{{ $t('commen.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 批量上传 -->
    <el-dialog :title="$t('teamDoc.temp.upTemps')" v-model="flagTwo" width="30%" destroy-on-close class="batchDialog">
      <el-form :model="form1" :rules="rules1" ref="multipleRef">
        <el-form-item :label="$t('teamDoc.temp.file')" :label-width="formLabelWidth" required class="pLUploadFileitem">
          <uploadFile :limit="999" ref="pLUploadFile" :multiple="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="flagTwo = false">{{ $t('commen.cancel') }}</el-button>
        <el-button type="primary" @click="batchEdit(multipleRef)">{{ $t('commen.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { Delete, Plus, Edit } from '@element-plus/icons-vue'
import navigationTitle from '../components/newUiModule/navigation-title.vue'
import { apiDeleteAllTemplate, apiUpdateTemplate, apiCreateTeamTemplateTree, apiBatchUpload, apiDeleteTemplateById, apiTeamTemplateTree } from "@/api/teamKnowdge/teamTemplateApi"
import uploadFile from '@/views/components/uploadFile/index.vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

const { proxy } = getCurrentInstance() as any

const route = useRoute()
const ruleFormRef = ref<FormInstance>()
const UploadFile = ref<any>()
const pLUploadFile = ref<any>()
const multipleRef = ref<FormInstance>()

const dialogTitle = ref('')
const searchData = ref({
  name:"",
  title:"",
})
const ruleForm = ref({
  classify: "",
  title: "",
  name: ""
})
const dictDetailList = ref([])
const tableData = ref([])
const Dialogloading = ref(false)
const total = ref(0)
const page = ref(1)
const pageSize = ref(6)
const flag = ref(false)
const form = ref({
  id: "",
  realName: "",
})
const formLabelWidth = ref('120px')
const rows = ref([])
const isAdd = ref(false)
const flagTwo = ref(false)
const form1 = ref({

})

// 删除全部
const deleteItemAll = () => {
  ElMessageBox.confirm(proxy.$t('teamDoc.temp.tip4'), proxy.$t('提示'), {
    confirmButtonText: proxy.$t('commen.confirm'),
    cancelButtonText: proxy.$t('commen.cancel'),
    type: 'warning'
  })
    .then(() => {
      apiDeleteAllTemplate({ teamId: route.query.teamId }).then((res) => {
        if (res.code == 200) {
          ElMessage.success(proxy.$t('teamDoc.temp.tip5'))
          search()
        }
      })
      // console.log(res,"全部模板删除")
    })
    .catch(() => {

    })
}
const resetForm = () => {
  searchData.value.name = ""
  searchData.value.title = ""
  search()
}
const searchForm = () => {
  search()
}

const selectRow = (val: any) => {
  rows.value = val
}
const addItem = () => {
  dialogTitle.value = proxy.$t("teamDoc.temp.btn2")
  flag.value = true
  //   this.form.parentId = "";
  form.value.realName = ""
  form.value.id = ""
  isAdd.value = true
}
const edit = (row) => {
  dialogTitle.value = proxy.$t("teamDoc.temp.editTemp")
  isAdd.value = false
  flag.value = true
  form.value.id = row.id
  form.value.realName = row.realName
  //   this.form.parentId = `${row.parentId}`;
}

const saveEdit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (!UploadFile.value.fileLis.length && isAdd.value) {
        ElMessage.error(proxy.$t('teamDoc.temp.tip6'))
        return
      }
      let formData = new FormData()
      formData.append("id", form.value.id)
      formData.append("realName", form.value.realName)
      formData.append("teamId", route.query.teamId as string)
      if (UploadFile.value.fileLis.length) {
        formData.append("file", UploadFile.value.fileLis[0].raw)
      }
      if (form.value.id) {
        await apiUpdateTemplate(formData).then((res) => {
          if (res.code == 200) {
            ElMessage.success(res.msg)
            flag.value = false
            search()
          }
        })
      } else {
        await apiCreateTeamTemplateTree(formData).then((res) => {
          if (res.code == 200) {
            ElMessage.success(res.msg)
            flag.value = false
            search()
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const batchItem = () => {
  //   this.form1.parentId = "";
  flagTwo.value = true
}

const batchEdit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!', pLUploadFile.value.fileLis.length)
      if (!pLUploadFile.value.fileLis.length) {
        ElMessage.error(proxy.$t('teamDoc.temp.tip6'))
        return
      }
      let formData = new FormData()
      formData.append("teamId", route.query.teamId as string)
      pLUploadFile.value.fileLis.forEach((item) => {
        formData.append("files", item.raw)
      })
      let res = await apiBatchUpload(formData)
      if (res.code == 200) {
        ElMessage.success(res.msg)
        flagTwo.value = false
        search()
      }

    } else {
      console.log('error submit!', fields)
    }
  })
}

const del = (row) => {
  let oParam = { id: row.id, teamId: route.query.teamId }
  ElMessageBox.confirm('此操作将永久删除该模板, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await apiDeleteTemplateById(oParam)
    if (res.code == 200) {
      ElMessage.success(res.msg)
      search()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: proxy.$t('teamDoc.temp.tip11')
    })
  })
}
const sizeChange = (val) => {
  pageSize.value = val
  search()
}
const currentPage = (val) => {
  page.value = val
  search()
}
const search = async () => {
  Dialogloading.value = true
  let params = {
    teamId: route.query.teamId,
    page: page.value - 1,
    size: pageSize.value,
    type: searchData.value.title,
    realName: searchData.value.name
  }
  let res = await apiTeamTemplateTree(params)
  if (res.code == 200) {
    tableData.value = res.data.rows
    total.value = res.data.total
    Dialogloading.value = false
  }
  Dialogloading.value = false
}
onMounted(() => {
  search()
})
</script>


<style scoped lang="scss">
.templateContentDetail {

  background: #fff;
  border-radius: 10px;

  :deep(.el-divider--horizontal) {
    display: block;
    height: 1px;
    width: 100%;
    margin: 15px 0;
  }

  .header {
    margin: 20px;

    .searchInput {
      width: 200px;
    }
  }

  .content-top {
    margin: 0 20px;
    padding: 20px 0px;
  }
}

.batchDialog {
  :deep(.el-dialog) {
    max-height: 600px;
  }

  .pLUploadFileitem {
    .uploadFile {
      max-height: 350px;
      overflow: auto;
    }
  }
}
</style>